/*
 *  Copyright 2013 National Institute of Advanced Industrial Science and Technology
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.sss.server;

import static org.sss.common.Utils.closeDataReceivers;

import java.lang.reflect.Method;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.sss.common.Bucket;
import org.sss.common.CommonStatus;
import org.sss.common.DataReceiver;
import org.sss.common.Inlet;
import org.sss.common.KeyValues;
import org.sss.common.TaskSliceSubmitter;
import org.sss.common.io.DataReader;
import org.sss.mapreduce.Configuration;
import org.sss.mapreduce.Decoder;
import org.sss.mapreduce.Reducer;
import org.sss.mapreduce.SssException;
import org.sss.mapreduce.StorageNode;
import org.sss.util.CallbackInterface;

public class ReduceTask extends ReduceTaskBase<KeyValues> {
  private static Logger logger = SssServer.getLogger(ReduceTask.class);

  public ReduceTask(TaskSet taskSet,
                    UUID jobID,
                    SssServerResource sssResource,
                    Configuration conf,
                    StorageNode storageNode,
                    Inlet inlet,
                    Class<? extends Reducer> reducerClass,
                    List<org.sss.common.Outlet> outletList,
                    CallbackInterface<CommonStatus> doneCallback) throws SssException {
    super(taskSet, jobID, sssResource, conf, storageNode, inlet, reducerClass, outletList, doneCallback);
  }

  @Override
  protected void submitReadTaskSlice(int i) throws SssException {
    DataReader r = getIOManager().createKeyValueReader(
        getConfiguration(), getStorageNode(), getInputGID(), i,
        new TaskSliceSubmitter<List<KeyValues>>(getWKTP(), this));
    submitReadRequest(r);
  }

  @Override
  public void handle(List<KeyValues> kvss) {
    try {
      SssServerConfiguration sssConf = getSssServerConfiguration();
      List<DataReceiver<Bucket>> cache = getOutlets().getTLPutters(sssConf.reduce_output_cache_nbytes);
      Object[] args = createArguments(createContext(), 2, cache);

      final Decoder keyDecoder = getKeyDecoder();
      final Decoder valDecoder = getValueDecoder();

      Method reduceMethod = getProcInfo().getMethod();
      Reducer reducer = getProc();
      for (KeyValues kvs: kvss) {
        args[1] = keyDecoder.decode(kvs.key);
        args[2] = decodingIterator(valDecoder, kvs.values);
        checkCanceled();
        reduceMethod.invoke(reducer, args);
      }
      closeDataReceivers(cache);
    } catch (Throwable e) {
      handleExceptionInHandle(e, "Error in reduce task. Cancels tasks.");
    } finally {
      for (KeyValues kvs: kvss) {
        kvs.values.close();
      }
      logger.debug("completing a ReduceTaskSlice.");
    }
  }
}
